// pages/toPay/toPay.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user: '',
    user_adress: '请选择收货地址',
    state: '外卖配送',
    states: ['外卖配送', '到店自取'],
    foods: [],
    total: 0,
    storeName: '',
    storeDetail: {}
  },
  changeState1() {
    this.setData({
      state: this.data.states[0]
    })
  },
  changeState2() {
    this.setData({
      state: this.data.states[1]
    })
  },
  chooseLocationhandler(e) {
    wx.chooseLocation({
      latitude: 0,
      longitude: 0,
      success: (result) => {
        this.setData({
          user_adress: result.name
        })
      }
    })
  },
  getTotal() {
    var all = 0
    for (var i of this.data.foods) {
      all += i.price * i.num
      this.setData({
        total: all
      })
    }
  },
  payHandler() {
    let str = '请选择收货地址'
    let state = this.data.state
    let states = this.data.states
    if (this.data.user_adress != str&& this.data.user_adress!='' && state == states[0]) {
      wx.navigateTo({
        url: '/pages/payOline/payOline?totalPrice=' + this.data.total + '&&storeName=' + this.data.storeDetail.storeName + '&&adress=' + this.data.user_adress
      })
    } else if (state == states[1]) {
      wx.navigateTo({
        url: '/pages/payOline/payOline?totalPrice=' + this.data.total + '&&storeName=' + this.data.storeDetail.storeName + '&&adress=' + this.data.storeDetail.adress
      })
    } else {
      wx.showToast({
        title: '请选择收货地址',
        icon: 'error'
      })
    }
  },
  yunGetStoreDetail(table, name) {
    let db = wx.cloud.database()
    let that = this
    db.collection(table)
      .where({
        storeName: name
      })
      .get({
        success: (res) => {
          that.setData({
            storeDetail: res.data[0]
          })
        }
      })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      foods: wx.getStorageSync('order'),
      user: wx.getStorageSync('Tel'),
      storeName: options.storeName
    })
    let storeName = this.data.storeName
    this.yunGetStoreDetail('CR_stores', storeName)
    this.getTotal()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})